﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using MusicFluent.Controls;
using MusicFluent.Models;
using MusicFluent.Views;
using NetEasyMusic.Lib.Data;
using NetEasyMusic.Lib.Models;

namespace MusicFluent.MusicViews;

public partial class ArtistView : UserControl
{
    public ArtistView(ArtistModel artist, string cookie)
    {
        _artist = artist;
        _cookie = cookie;
        InitializeComponent();
    }

    private readonly ArtistModel _artist;
    private readonly string _cookie;

    protected override async void OnInitialized()
    {
        base.OnInitialized();
        using var artist = new Artist(_cookie);
        var model = await artist.GetArtist(_artist.Id);
        ArtistImage.Source = $"{model.PicUrl}?param=250y250";
        NameBlock.Text = model.Name;
        TopList.ItemsSource = await artist.GetTopSongsAndPic(model.HotSongs);
        AlbumList.ItemsSource = await artist.GetArtistAlbums(_artist.Id);
        OtherList.ItemsSource = await artist.GetSimilar(_artist.Id);
        BasicBlock.Text = model.BasicDesc;
    }

    private void ArtistTapped(object? sender, TappedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not ArtistModel model) return;
        var view = ViewOpera.GetView<MainWindow>(Parent);
        if (view == null) return;
        var artist = new ArtistView(model, view.Cookie);
        view.Navigate(artist);
    }

    private void AlbumTapped(object? sender, TappedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not AlbumModel model) return;
        var view = ViewOpera.GetView<MainWindow>(Parent);
        if (view == null) return;
        var artist = new AlbumView(model.Id);
        view.Navigate(artist);
    }

    private async void DescTapped(object? sender, TappedEventArgs e)
    {
        if (sender is not TextBlock block) return;
        await MusicDialog.ShowMusicDialog(new TextBlock()
        {
            Text = block.Text, Width = 450,
            TextWrapping = TextWrapping.WrapWithOverflow
        }, (Visual)VisualRoot!);
    }
}